import { NIcon } from 'naive-ui';
import { h } from 'vue';
import DyIcon from '@/components/dy-icon/index.vue';

export const renderIcon = (iconName: string) => {
  return () => h(NIcon, { size: 17 }, { default: () => h(DyIcon as any, { icon: iconName }) });
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data: any[], id: string, parentId?: string, children?: string) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  };

  const childrenListMap: any = {};
  const nodeIds: any = {};
  const tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o: any) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 将对象转成 x-www-form-urlencoded
 */
export function toFormUrlEncoded(params: any) {
  const formData = new URLSearchParams();
  Object.keys(params).forEach((key) => {
    const value = params[key];
    if (value !== null && value !== undefined && value !== '') {
      formData.append(key, value);
    }
  });
  return formData.toString();
}

/**
 * 用于Tree组件全选
 * @param data 接口返回的数据(注意id与key的对应)
 * @returns
 */
export function getAllNodeKeys(data: any[]) {
  return data.reduce((keys: any[], node) => {
    keys.push(node.id);
    if (node.children?.length) {
      keys.push(...getAllNodeKeys(node.children));
    }
    return keys;
  }, []);
}
